package com.bifrost.listener;

import com.bifrost.event.ClearBonusEvent;
import com.bifrost.service.ClearBonusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Async
@Component
public class ClearBonusListener implements ApplicationListener<ClearBonusEvent> {

    private static ConcurrentHashMap map = new ConcurrentHashMap();

    @Autowired
    ClearBonusService clearBonusService;

    @Override
    public void onApplicationEvent(ClearBonusEvent event) {
        Long storeId = (Long) event.getSource();
        List<Long> list = (List<Long>) map.get("stores");
        try {
            if (list == null) {
                list = new ArrayList<Long>();
                list.add(storeId);
                map.put("stores", list);
                map.put("currentStore", storeId);
                clearBonusService.clear(storeId);
                log.info("清空门店积分完成");
                return;
            }
            if (!list.contains(storeId)) {
                list.add(storeId);
                map.put("currentStore", storeId);
                clearBonusService.clear(storeId);
                log.info("清空门店积分完成");
                return;
            }
        } finally {
            list.remove(storeId);
        }

/*      map.containsKey()
        HttpSession session = (HttpSession)event.getSource();
        List<Long> list = (List<Long>)session.getAttribute("stores");
        Long storeId = (Long)session.getAttribute("currentStore");
        if(clearBonusService.clear(storeId)){
            list.remove(storeId);
        }
        log.info("清空门店积分完成");*/
    }
}
